$(function(){



	var MessageBoardView = Backbone.View.extend({
		
		
		el: $('#messageBoardView'),



	    events: {
	      'click #messageBoardView-addBoard': 'addItem'
	    },

        initTinyMce: function () {
            $('#newBoardDescriptionInput').tinymce({
                script_url : 'lib/tinymce/jscripts/tiny_mce/tiny_mce.js',
                theme: "advanced",
                skin: "o2k7",
                skin_variant: "black",

                // Theme options
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_resizing: false
            });
        }, initialize: function()
	    {
	    	_.bindAll(this, 'render', 'addItem');
	    	this.model=new Messageboard();
            this.topicTemplate= $('#messageboardView-board-template');
            this.containerElement=$('#messageboardView-boards')[0];
            this.initTinyMce();

	    },
	    
	    addItem: function(addItemEvent){
            tinyMCE.triggerSave();
            var newTitle = $('#newBoardTitleInput').val();
            var newDescription=$('#newBoardDescriptionInput').tinymce().getContent();
            var newTopic=new Topic;
            newTopic.set({title: newTitle});
            newTopic.set({description: newDescription});
            this.model.get("topics").add(newTopic);
            this.render();
        },
	    
	    render: function()
	    {
            var topics=this.model.get("topics");
            var templateElement=this.topicTemplate;

            $(this.containerElement).empty();

            for(var i=0;i<topics.length;i++)
            {
                var topic=topics.at(i);
                var newTopicElement=templateElement.clone();
                var newTopicElementId="messageboardView-board"+i;
                newTopicElement[0].setAttribute("id",newTopicElementId);

                var newTitleElement=$("#messageboardView-board-template-title",newTopicElement);
                var newTitleElementId=newTopicElementId+"-title";
                newTitleElement[0].setAttribute("id",newTitleElementId);
                newTitleElement[0].innerText=topic.get("title");

                var newDescriptionElement=$("#messageboardView-board-template-description",newTopicElement);
                var newDescriptionElementId=newTopicElementId+"-description";
                newDescriptionElement[0].setAttribute("id",newDescriptionElementId);
                newDescriptionElement[0].innerHTML=topic.get("description");

                this.containerElement.appendChild(newTopicElement[0]);
            }

	    }
		
	});

    var view;
    view = new MessageBoardView();
    view.render();

}
);